package picturetaker.application;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.concurrent.BlockingQueue;

import javax.naming.NamingException;
import javax.swing.ImageIcon;

import picturetaker.utility.ApplicationConstants;
import picturetaker.utility.Thumbnail;
import picturetaker.domain.Picture;
import picturetaker.persistence.JNDIFactory;

public class FileIOThread implements Runnable, ApplicationConstants {

	boolean running = true;
	
	BlockingQueue<Picture> queueFromCam = null;
	
	BlockingQueue<Picture> queueToPersistence = null;
	
	private String basicPath = null;
	
	public FileIOThread(BlockingQueue<Picture> queueFromCam, BlockingQueue<Picture> queueToPersistence)  {
		this.queueFromCam = queueFromCam;
		this.queueToPersistence = queueToPersistence;
		try {
			this.basicPath = JNDIFactory.getInstance().getEnvirontmentAsString("imagePath");
		} catch (NamingException e) {
		}
	}
	
	public void run() {
		Picture pic = null;
		String pictureName = null;
		while(running){
			try {
				pic = queueFromCam.take();
				pic.setThumbnail(getThumbnail(pic.getPicData().getPic()));
				pictureName = String.valueOf(System.currentTimeMillis()) + ".jpg";
				pic.setPath(createAndWritePath(pic, true) + SLASH + pictureName);
				pic.getPicData().setPath(createAndWritePath(pic, false) + SLASH + pictureName);
				if(writeToFile(pic.getPath() , pic.getThumbnail()))
					if(writeToFile(pic.getPicData().getPath(), pic.getPicData().getPic()))
						queueToPersistence.put(pic);
			} catch (InterruptedException e) {
			} catch (IOException e){}
		}
	}
	
	private boolean writeToFile(String fileString, byte[] data){
		File file = null;
		FileOutputStream fileOut = null;
		file = new File(fileString);
		try {
			fileOut = new FileOutputStream(file);
			fileOut.write(data);
			fileOut.flush();
			fileOut.close();
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		return true;
	}
	
	private String createAndWritePath(Picture  pic, boolean isThumbnail){
		String dateFolder = DateFormat.getDateInstance().format(pic.getDate()).replace(DOT, UNDERSCORE);
		StringBuffer sb = new StringBuffer()
			.append(this.basicPath)
			.append(SLASH)
			.append(isThumbnail ? PATH_THUMBNAIL : PATH_PICTURE)
			.append(SLASH)
			.append(pic.getCamera().getCameraName())
			.append(pic.getCamera().getId())
			.append(SLASH)
			.append(dateFolder);
		File file = new File(sb.toString());
		if(!file.exists())
			file.mkdirs();
		if(file.list().length > 5000){			
			dateFolder = DateFormat.getTimeInstance().format(pic.getDate()).replace(COLON, UNDERSCORE);
			sb
				.append(UNDERSCORE)
				.append(VON)
				.append(UNDERSCORE)
				.append(dateFolder);
			file = new File(sb.toString());
			file.mkdirs();
		}
		return sb.toString();
	}

	private byte[] getThumbnail(byte[] pic) throws IOException {
		ImageIcon icon = new ImageIcon(pic);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		Thumbnail.createThumbnail(icon.getImage(), out, THUMBNAIL_MAXDIM);
		return out.toByteArray();
	}
}
